const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
import {
  showMsg
} from '../../../../../utils/config.js'
import {
  validateEmoji,
  validateSpecial
} from '../../../../../utils/validate.js'
import {
  reqSpaceEdit,
  reqSpaceImage,
  reqDeviceBySpaceId,
  reqDeviceByImei,
  reqDeviceAdd,
  reqDeviceUnBind,
  reqAlarmReceiverList,
  reqReceiverSpaceAdd,
  reqAlarmReceiverBySpaceId
} from '../../../../../request/api'
Page({
  data: {
    navHeight: app.globalData.navHeight + 'px', //头部距离
    bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离

    currentTab: 0,

    spaceInfo: {},

    // 接警人开始
    showPeopleCall: false,
    alarmReceiverList: [],
    alarmPage: 1,
    alarmIsNextPage: true,
    alarmReceiverArr: [], //最终提交值id集合
    selAlarmReceiverArr: [], //展示渲染页面
    alarmReceiverIdList1: [],
    alarmReceiverIdList2: [],
    alarmReceiverIdList3: [],
    alarmReceiverIdList4: [],

    expanded: true,
    level: 1,
    levelList: [{
        value: 1,
        name: "一级",
      },
      {
        value: 2,
        name: "二级",
      },
      {
        value: 3,
        name: "三级",
      },
      {
        value: 4,
        name: "四级",
      },
    ],
    // 接警人结束
    disabledBtn: false,
  },


  onLoad(e) {
    console.log('load', e);
    this.setData({
      spaceInfo: JSON.parse(e.item)
    })
    this.setData({
      'form.id': this.data.spaceInfo.id,
      'form.orgId': this.data.spaceInfo.orgId,
    })
    this.AlarmReceiverBySpaceId()
    this.getAlarmReceiverList() //获取接警人列表
  },

  onShow() {

  },



  // -----------------接警人开始----------------
  // 空间id获取接警人列表
  async AlarmReceiverBySpaceId() {
    const res = await reqAlarmReceiverBySpaceId(this.data.form.id)
    let {
      rows
    } = res.data
    console.log("rows接警人列表", rows);
    if (rows && rows.length) {
      rows.sort((a, b) => a.level - b.level)
      this.setData({
        selAlarmReceiverArr: rows
      })
    } else {
      this.setData({
        selAlarmReceiverArr: []
      })
    }
  },


  // 点击展示接警人弹窗
  async clickShowPeopleCall(e) {
    const {
      selAlarmReceiverArr
    } = this.data
    if (selAlarmReceiverArr != selAlarmReceiverArr.length) {
      selAlarmReceiverArr.forEach((result, index) => {
        // 勾选对应级别的接警人
        const checkbox = this.selectComponent(`.checkboxes-${result.id}`);
        checkbox.toggle();
      })
    }
    // 级别禁用
    let list = this.data.alarmReceiverList.map(item => {
      item.disabled = false;
      item.level = ''
      this.data.selAlarmReceiverArr.forEach(item2 => {
        if (item.id == item2.id) {
          console.log('==item2', item2);
          item.disabled = true;
          item.level = item2.level
        }
      })
      return item
    })
    this.setData({
      showPeopleCall: true,
      alarmReceiverList: list,
    })
  },
  // 点击关闭接警人弹窗
  async closePeopleCall() {
    //   清空选中的状态
    this.data.selAlarmReceiverArr.forEach((result, index) => {
      console.log(result);
      const checkbox = this.selectComponent(`.checkboxes-${result.id}`);
      checkbox.toggle();
    })

    let list = this.data.alarmReceiverList.map(item => {
      item.disabled = false;
      return item
    })
    this.setData({
      showPeopleCall: false,
      alarmReceiverArr: [],
      alarmReceiverList: list, //取消禁用
    })
  },

  //接警人新增
  async receiverSpaceAddFun() {
    let {
      selAlarmReceiverArr,
    } = this.data

    let alarmReceiverIdList1 = []
    let alarmReceiverIdList2 = []
    let alarmReceiverIdList3 = []
    let alarmReceiverIdList4 = []
    selAlarmReceiverArr.forEach((item) => {
      switch (item.level) {
        case 1:
          alarmReceiverIdList1.push(item.id)
          break
        case 2:
          alarmReceiverIdList2.push(item.id)
          break
        case 3:
          alarmReceiverIdList3.push(item.id)
          break
        case 4:
          alarmReceiverIdList4.push(item.id)
          break
        default:
          return
      }
    })
    if (alarmReceiverIdList1.length > 6) return showMsg("一级接警人最多设置6个")
    if (alarmReceiverIdList2.length > 6) return showMsg("二级接警人最多设置6个")
    if (alarmReceiverIdList3.length > 6) return showMsg("三级接警人最多设置6个")
    if (alarmReceiverIdList4.length > 6) return showMsg("四级接警人最多设置6个")
    const res = await reqReceiverSpaceAdd({
      spaceId: this.data.form.id,
      alarmReceiverIdList1,
      alarmReceiverIdList2,
      alarmReceiverIdList3,
      alarmReceiverIdList4,
    })
    if (res.code != 20000) return showMsg(res.message);
  },

  //  获取接警人列表
  async getAlarmReceiverList() {
    let params = {
      orgId: this.data.form.orgId,
      userId: app.globalData.userId,
      roleName: app.globalData.rolename,
    }
    const res = await reqAlarmReceiverList(this.data.alarmPage, 99, params)
    if (res.code !== 20000) return showMsg(res.message, "error")
    let {
      rows
    } = res.data
    console.log(rows);
    if (this.data.alarmPage === 1) {
      this.setData({
        alarmReceiverList: rows,
        alarmIsNextPage: true
      })
    } else if (this.data.alarmPage > 1 && rows.length) {
      this.setData({
        alarmReceiverList: this.data.alarmReceiverList.concat(rows),
        alarmIsNextPage: true
      })
    } else if (this.data.alarmPage > 1 && !rows.length) {
      showMsg('已经到底啦~')
      this.setData({
        alarmIsNextPage: false
      })
    }
    if (this.data.showPeopleCall) {
      this.clickShowPeopleCall()
    }
  },

  // 滚动到底部触发
  alarmReceiverLower() {
    if (!this.data.alarmIsNextPage) return
    this.setData({
      alarmPage: this.data.alarmPage + 1,
    })
    this.getAlarmReceiverList()
  },

  levelChange(event) {
    this.setData({
      level: event.detail,
    });
  },
  // 获取alarmReceiverArr的值
  deviceChange(event) {
    this.setData({
      alarmReceiverArr: event.detail
    })
    // console.log(this.data.alarmReceiverArr,"alarmReceiverArr")
  },
  // 点击获取alarmReceiverArr的值
  deviceToggle(event) {
    const {
      id
    } = event.currentTarget.dataset;
    this.checkboxChange(id)
  },
  // 复选框变化渲染
  checkboxChange(id) {
    console.log('复选框变化渲染', id);
    const checkbox = this.selectComponent(`.checkboxes-${id}`);
    checkbox.toggle();
  },

  // 删除某个接警人
  deleteAlarmReceiver(e) {

    const {
      id,
      value
    } = e.currentTarget.dataset;

    Dialog.confirm({
        title: '温馨提示',
        message: '此操作将从安装点删除该接警人，是否继续？',
      })
      .then(async () => {

        let {
          alarmReceiverArr,
          selAlarmReceiverArr
        } = this.data
        alarmReceiverArr.forEach((item, index) => {
          if (item.id === id) {
            alarmReceiverArr.splice(index, 1)
          }
        })
        selAlarmReceiverArr.forEach((item, index) => {
          if (item.id === id) {
            selAlarmReceiverArr.splice(index, 1)
          }
        })
        this.setData({
          alarmReceiverArr,
          selAlarmReceiverArr
        })
        // this.checkboxChange(id)
        this.closePeopleCall()
        this.receiverSpaceAddFun() //接警人新增
      })
      .catch(() => {});

  },
  // 确定选择接警人
  async confirmPeopleCall() {
    let {
      alarmReceiverArr,
      alarmReceiverList,
      level
    } = this.data
    // 1、获取新的勾选
    const enabledReceivers = alarmReceiverList.filter(item => !item.disabled);
    const updatedReceivers = enabledReceivers.map(item => {
      const citem = alarmReceiverArr.find(citem => item.id === citem);
      if (citem !== undefined) {
        item.level = this.data.level;
        return item;
      }

      return null;
    }).filter(item => item !== null);

    // 2、合并新旧勾选
    const newSelAlarmReceiverArr = [...this.data.selAlarmReceiverArr, ...updatedReceivers]
      .sort((a, b) => a.level - b.level);

    console.log('newSelAlarmReceiverArr', newSelAlarmReceiverArr);
    // 3、更新
    let alarmReceiverIdList1 = []
    let alarmReceiverIdList2 = []
    let alarmReceiverIdList3 = []
    let alarmReceiverIdList4 = []
    newSelAlarmReceiverArr.forEach((item) => {
      switch (item.level) {
        case 1:
          alarmReceiverIdList1.push(item.id)
          break
        case 2:
          alarmReceiverIdList2.push(item.id)
          break
        case 3:
          alarmReceiverIdList3.push(item.id)
          break
        case 4:
          alarmReceiverIdList4.push(item.id)
          break
        default:
          return
      }
    })
    if (alarmReceiverIdList1.length > 6) return showMsg("一级接警人最多设置6个")
    if (alarmReceiverIdList2.length > 6) return showMsg("二级接警人最多设置6个")
    if (alarmReceiverIdList3.length > 6) return showMsg("三级接警人最多设置6个")
    if (alarmReceiverIdList4.length > 6) return showMsg("四级接警人最多设置6个")
    // if (alarmReceiverArr.length > 6) return showMsg("接警人最多设置6个")
    const res = await reqReceiverSpaceAdd({
      spaceId: this.data.form.id,
      alarmReceiverIdList1,
      alarmReceiverIdList2,
      alarmReceiverIdList3,
      alarmReceiverIdList4,
      // alarmReceiverIdList1: this.data.valueInfo == 1 ? this.data.alarmReceiverArr : this.data.alarmReceiverIdList1.map(item => item.id),
      // alarmReceiverIdList2: this.data.valueInfo == 2 ? this.data.alarmReceiverArr : this.data.alarmReceiverIdList2.map(item => item.id),
      // alarmReceiverIdList3: this.data.valueInfo == 3 ? this.data.alarmReceiverArr : this.data.alarmReceiverIdList3.map(item => item.id),
      // alarmReceiverIdList4: this.data.valueInfo == 4 ? this.data.alarmReceiverArr : this.data.alarmReceiverIdList4.map(item => item.id),
    })
    if (res.code != 20000) return showMsg(res.message);
    // await this.receiverSpaceAddFun()
    await this.closePeopleCall() //关闭弹窗
    this.AlarmReceiverBySpaceId() // 空间id获取接警人列表
  },

  swichNav(e) {
    let {
      current
    } = e.currentTarget.dataset
    this.setData({
      currentTab: current
    })
  },

  bindChangeTab(e) {
    let {
      current
    } = e.detail
    this.setData({
      currentTab: current
    })
  },

})